package com.jushu.storbox.view.resolve;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.os.Message;

import com.jushu.storbox.adapter.DownloadTranslateAdapter;
import com.jushu.storbox.constant.UiConstant;
import com.jushu.storbox.database.DAOFactory;
import com.jushu.storbox.database.IDownloadFileDao;
import com.jushu.storbox.entities.DownloadObject;
import com.jushu.storbox.handler.ClientExceptionRelateHandler;
import com.jushu.storbox.manager.CatchManager;
import com.jushu.storbox.manager.DownloadTaskManager;
import com.jushu.storbox.operation.group.BasicItemOperation;

public class DownloadResolver extends
		TranslateResolver<DownloadObject, 
		BasicItemOperation<DownloadObject>,
		DownloadTranslateAdapter> {

	ArrayList<DownloadObject> list = new ArrayList<DownloadObject>();
	IDownloadFileDao downloadDao = null;
	
	public DownloadResolver(Context context) {
		super(context);
	}

	@Override
	protected DownloadTranslateAdapter initTemplateAdapter() {
		return new DownloadTranslateAdapter(context, list);
	}

	@Override
	protected BasicItemOperation<DownloadObject> initAdapterOperation() {
		return new BasicItemOperation<DownloadObject>(){};
	}

	@Override
	protected void loadDataList() {
		List<DownloadObject> catchList = new ArrayList<DownloadObject>();
		
		List<DownloadObject> dbDownloadList = getDownloadDao().getDownloadFileList();
		for(DownloadObject tempObj : dbDownloadList) {
			DownloadObject catchObj = CatchManager.getInstance().getDownloadObject(tempObj);
			if(catchObj != null) {
				catchList.add(catchObj);
			} else {
				catchList.add(tempObj);
			}
		}
		this.resetDatas(catchList);
		msgHandler.sendEmptyMessage(UiConstant.REFRESH_LIST_COMPLATE);
	}

	private IDownloadFileDao getDownloadDao() {
		if(downloadDao == null) {
			downloadDao = DAOFactory.instance(context).getDownloadFileDao();
		}
		return downloadDao;
	}

	@Override
	public void stopAllTasks() {
		synchronized(list) {
			for(DownloadObject downItem : list) {
				DownloadTaskManager.stopTask(context, downItem);
			}
		}
	}

	@Override
	public void startAllTasks() {
		synchronized(list) {
			for(DownloadObject downItem : list) {
				DownloadTaskManager.startTask(context, downItem);
			}
		}
	}

	@Override
	public void deleteAllTasks() {
		synchronized(list) {
			for(DownloadObject downItem : list) {
				DownloadTaskManager.cancelTask(context, downItem);
			}
		}
		getAdapter().cleanListDatasAndNotify();
	}

	ClientExceptionRelateHandler msgHandler = new ClientExceptionRelateHandler() {

		@Override
		public void handleMessage(Message msg) {
			switch(msg.what) {
			case UiConstant.REFRESH_LIST_COMPLATE:
				onRefreshComplete();
				break;
			default:
				super.handleMessage(msg);
			}
		}

		@Override
		public Context getContext() {
			return context;
		}
	};
}
